'use strict';
//const Controller = require('egg').Controller;
const common = require('../../libs/common');

module.exports = app => {
  class LoginController extends app.Controller {
    async index(ctx) {
      let username=ctx.request.body.username;
      let password=ctx.request.body.password;
      if(username==null){
        ctx.body={ok:false,msg:'用户名不可为空'};
      }
      if(password==null){
        ctx.body={ok:false,msg:'密码不可为空'};
      }
      password=common.md5(password+common.MD5_SUFFIX);

      let result = await this.app.mysql.get('tc_users',{username:username}); 
      if(!result || result==null){
        ctx.status=401;
        ctx.body={ok:false,msg:'此用户不存在'};
      }else{
        if (result.password!=password) {
            ctx.status=401;
            ctx.body={msg:'密码不正确'};
        }else {
            const token = app.jwt.sign({ user_id: result.user_id }, app.config.jwt.secret,{ expiresIn: 30 * 60 });
            result['token']=token;
            result['roles']=['admin'];
            ctx.body=result;
        }
      }
    }
    async register(ctx) {
      const body=ctx.request.body;
      let username=body.username;
      if(username==null){
        ctx.status=401;
        ctx.body={msg:'用户名不可为空'};
      }
      let password=body.password;
      let code =password;
      if(password==null){
        ctx.status=401;
        ctx.body={ok:false,msg:'密码不可为空'};
      }
      let result = await this.app.mysql.get('tc_users',{username:username});
      if(result.username){
         ctx.status=401;
         ctx.body={ok:false,msg:'用户名已存在'};
      }else{
         password=common.md5(password+common.MD5_SUFFIX);
         let result = await this.app.mysql.insert('tc_users',{username:username,password:password});
         ctx.body={ok:true,msg:'注册成功'};
      }
    }
    async logout(ctx) {


      ctx.body='退出成功'
    }
  }
  return LoginController;
};

